package com.zhr.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.zhr.common.ResultData;
import com.zhr.common.ResultState;
import com.zhr.tools.ToIco;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.ByteArrayOutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author ZHR
 */
@RestController
public class ImageToIcoController {
    @GetMapping("support-formats")
    public ResultData<Set<String>> getSupportedImageFormats() {
        List<String> supportedImageFormats = ToIco.getSupportedImageFormats();
        Set<String> set = new HashSet<>();
        supportedImageFormats.forEach(e -> set.add(e.toUpperCase()));
        return new ResultData<>(set);
    }

    @PostMapping("image2ico")
    public ResponseEntity<?> image2ico(@RequestParam Integer size, MultipartHttpServletRequest request) throws Exception {
        Iterator<String> iter = request.getFileNames();
        if (!iter.hasNext()) {
            return new ResponseEntity<>(new ResultData<>(ResultState.BIZ_FAIL, "无文件"), HttpStatus.OK);
        }
        String name = iter.next();
        List<MultipartFile> files = request.getFiles(name);
        if (files.size() <= 0) {
            return new ResponseEntity<>(new ResultData<>(ResultState.BIZ_FAIL, "无文件."), HttpStatus.OK);

        }
        MultipartFile f = files.get(0);
        String filename = f.getOriginalFilename();
        if (StrUtil.isBlank(filename)) {
            return new ResponseEntity<>(new ResultData<>(ResultState.BIZ_FAIL, "未读取到文件名."), HttpStatus.OK);
        }
        String format = filename.substring(filename.lastIndexOf('.') + 1);

        boolean supported = ToIco.isSupported(format);
        if (!supported) {
            return new ResponseEntity<>(new ResultData<>(ResultState.BIZ_FAIL, "文件格式不支持."), HttpStatus.OK);
        }
        String outName = filename.substring(0, filename.lastIndexOf('.'));
        ByteArrayOutputStream outputStream = ToIco.toIco(size, format, f.getInputStream());
        byte[] bytes = outputStream.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition",
                "attachment; filename=" + outName + "_" + size + ".ico");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(bytes.length)
                .contentType(MediaType.parseMediaType("image/x-icon"))
                .body(bytes);
    }

    @PostMapping("image2icoBase64")
    public ResponseEntity<?> image2icoBase64(@RequestParam Integer size, MultipartHttpServletRequest request) throws Exception {
        Iterator<String> iter = request.getFileNames();
        if (!iter.hasNext()) {
            return new ResponseEntity<>(new ResultData<>("无文件"), HttpStatus.OK);
        }
        String name = iter.next();
        List<MultipartFile> files = request.getFiles(name);
        if (files.size() <= 0) {
            return new ResponseEntity<>(new ResultData<>("无文件."), HttpStatus.OK);
        }
        MultipartFile f = files.get(0);
        String filename = f.getOriginalFilename();
        if (StrUtil.isBlank(filename)) {
            return new ResponseEntity<>(new ResultData<>("未读取到文件名."), HttpStatus.OK);
        }
        String format = filename.substring(filename.lastIndexOf('.') + 1);
        String outName = filename.substring(0, filename.lastIndexOf('.'));
        ByteArrayOutputStream outputStream = ToIco.toIco(size, format, f.getInputStream());
        byte[] bytes = outputStream.toByteArray();
        String base64 = Base64.encode(bytes);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + outName + "_" + size + ".ico");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(base64.getBytes().length)
                //.contentType(MediaType.parseMediaType("image/x-icon"))
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(base64);
    }
}
